package com.cebbank.sz.cebtemplate.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author sucz
 * @create 2019/12/31 10:39
 */
public class Md5Util {

    private static final Logger logger=LoggerFactory.getLogger(Md5Util.class);

    public static String getMd5Str(String str) {
        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            logger.error(e.getMessage(),e);
        }

        byte[] bytes = messageDigest != null ? messageDigest.digest() : new byte[0];
        StringBuilder sb = new StringBuilder();

        for (byte aByte : bytes) {
            if (Integer.toHexString(255 & aByte).length() == 1) {
                sb.append("0").append(Integer.toHexString(255 & aByte));
            } else {
                sb.append(Integer.toHexString(255 & aByte));
            }
        }

        return sb.toString();
    }

    public static String getMd5BySpring(String str) {
        return DigestUtils.md5DigestAsHex(str.getBytes());
    }

    public static void main(String[] args) {
        System.out.println(getMd5Str("1234567").toUpperCase());
        System.out.println(getMd5BySpring("1234567").toUpperCase());
    }

}
